package com.jn.erp.web.api.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jn.erp.common.constant.UserConstants;
import com.jn.erp.common.exception.ServiceException;
import com.jn.erp.common.utils.StringUtils;
import com.jn.erp.web.api.sys.entity.SysDictData;
import com.jn.erp.web.api.sys.entity.SysDictType;
import com.jn.erp.web.api.sys.mapper.SysDictDataMapper;
import com.jn.erp.web.api.sys.mapper.SysDictTypeMapper;
import com.jn.erp.web.api.sys.service.SysDictTypeService;
import com.jn.erp.web.api.sys.utils.DictUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <pre>
 *
 * </pre>
 *
 * @author sunjiyong
 * @since 2024/8/28 15:45
 */
@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements SysDictTypeService {

    @Autowired
    private SysDictDataMapper dictDataMapper;

    /**
     * 根据字典类型查询字典数据
     *
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictData> selectDictDataByType(String dictType) {
        List<SysDictData> dictDatas = DictUtils.getDictCache(dictType);
        if (StringUtils.isNotEmpty(dictDatas)) {
            return dictDatas;
        }
        QueryWrapper<SysDictData> qw = new QueryWrapper();
        qw.eq("status", "0");
        qw.eq("dict_type", dictType);
        dictDatas = dictDataMapper.selectList(qw);
        if (StringUtils.isNotEmpty(dictDatas)) {
            DictUtils.setDictCache(dictType, dictDatas);
            return dictDatas;
        }
        return null;
    }


    /**
     * 校验字典类型称是否唯一
     *
     * @param dict 字典类型
     * @return 结果
     */
    @Override
    public boolean checkDictTypeUnique(SysDictType dict) {
        Long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId();
        QueryWrapper<SysDictType> qw = new QueryWrapper<>();
        qw.eq("dict_type", dict.getDictType());
        SysDictType dictType = baseMapper.selectOne(qw);
        if (StringUtils.isNotNull(dictType) && dictType.getDictId().longValue() != dictId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 重置字典缓存数据
     */
    @Override
    public void resetDictCache() {
        clearDictCache();
        loadingDictCache();
    }

    /**
     * 清空字典缓存数据
     */
    @Override
    public void clearDictCache() {
        DictUtils.clearDictCache();
    }


    /**
     * 加载字典缓存数据
     */
    @Override
    public void loadingDictCache() {
        QueryWrapper<SysDictData> qw = new QueryWrapper<>();
        qw.eq("status", "0");
        List<SysDictData> sysDictData = dictDataMapper.selectList(qw);
        Map<String, List<SysDictData>> dictDataMap = sysDictData.stream().collect(Collectors.groupingBy(SysDictData::getDictType));
        for (Map.Entry<String, List<SysDictData>> entry : dictDataMap.entrySet()) {
            DictUtils.setDictCache(entry.getKey(), entry.getValue().stream().sorted(Comparator.comparing(SysDictData::getDictSort)).collect(Collectors.toList()));
        }
    }

    @Override
    @Transactional
    public void deleteDictTypeByIds(Long[] dictIds) {
        for (Long dictId : dictIds) {
            SysDictType dictType = baseMapper.selectById(dictId);
            QueryWrapper<SysDictData> qw = new QueryWrapper<>();
            qw.eq("dict_type", dictType.getDictType());
            if (dictDataMapper.selectCount(qw) > 0) {
                throw new ServiceException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
            }
            baseMapper.deleteById(dictId);
            DictUtils.removeDictCache(dictType.getDictType());
        }
    }


    /**
     * 修改保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDictType(SysDictType dict) {
        SysDictType oldDict = baseMapper.selectById(dict.getDictId());
        dictDataMapper.updateDictDataType(oldDict.getDictType(), dict.getDictType());
        dict.setDictId(oldDict.getDictId());
        int row = baseMapper.updateById(dict);
        if (row > 0) {
            QueryWrapper<SysDictData> qw = new QueryWrapper<>();
            qw.eq("status", "0");
            qw.eq("dict_type", dict.getDictType());
            List<SysDictData> dictDatas = dictDataMapper.selectList(qw);
            DictUtils.setDictCache(dict.getDictType(), dictDatas);
        }
        return row;
    }
}
